{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Add chat history\n",
        "\n",
        "In many Q&A applications we want to allow the user to have a back-and-forth conversation, meaning the application needs some sort of \"memory\" of past questions and answers, and some logic for incorporating those into its current thinking.\n",
        "\n",
        "In this guide we focus on **adding logic for incorporating historical messages, and NOT on chat history management.** Chat history management is [covered here](/docs/expression_language/how_to/message_history).\n",
        "\n",
        "We'll work off of the Q&A app we built over the [LLM Powered Autonomous Agents](https://lilianweng.github.io/posts/2023-06-23-agent/) blog post by Lilian Weng in the [Quickstart](/docs/use_cases/question_answering/quickstart). We'll need to update two things about our existing app:\n",
        "\n",
        "1. **Prompt**: Update our prompt to support historical messages as an input.\n",
        "2. **Contextualizing questions**: Add a sub-chain that takes the latest user question and reformulates it in the context of the chat history. This is needed in case the latest question references some context from past messages. For example, if a user asks a follow-up question like \"Can you elaborate on the second point?\", this cannot be understood without the context of the previous message. Therefore we can't effectively perform retrieval with a question like this."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Setup\n",
        "### Dependencies\n",
        "\n",
        "We’ll use an OpenAI chat model and embeddings and a Memory vector store in this walkthrough, but everything shown here works with any [ChatModel](/docs/modules/model_io/chat) or [LLM](/docs/modules/model_io/llms), [Embeddings](/docs/modules/data_connection/text_embedding/), and [VectorStore](/docs/modules/data_connection/vectorstores/) or [Retriever](/docs/modules/data_connection/retrievers/).\n",
        "\n",
        "We’ll use the following packages:\n",
        "\n",
        "```bash\n",
        "npm install --save langchain @langchain/openai cheerio\n",
        "```\n",
        "\n",
        "We need to set environment variable `OPENAI_API_KEY`:\n",
        "\n",
        "```bash\n",
        "export OPENAI_API_KEY=YOUR_KEY\n",
        "```"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### LangSmith\n",
        "\n",
        "Many of the applications you build with LangChain will contain multiple steps with multiple invocations of LLM calls. As these applications get more and more complex, it becomes crucial to be able to inspect what exactly is going on inside your chain or agent. The best way to do this is with [LangSmith](https://smith.langchain.com/).\n",
        "\n",
        "Note that LangSmith is not needed, but it is helpful. If you do want to use LangSmith, after you sign up at the link above, make sure to set your environment variables to start logging traces:\n",
        "\n",
        "\n",
        "```bash\n",
        "export LANGCHAIN_TRACING_V2=true\n",
        "export LANGCHAIN_API_KEY=YOUR_KEY\n",
        "```"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Initial setup"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "import \"cheerio\";\n",
        "import { CheerioWebBaseLoader } from \"langchain/document_loaders/web/cheerio\";\n",
        "import { RecursiveCharacterTextSplitter } from \"langchain/text_splitter\";\n",
        "import { MemoryVectorStore } from \"langchain/vectorstores/memory\"\n",
        "import { OpenAIEmbeddings, ChatOpenAI } from \"@langchain/openai\";\n",
        "import { pull } from \"langchain/hub\";\n",
        "import { ChatPromptTemplate } from \"@langchain/core/prompts\";\n",
        "import { RunnableSequence, RunnablePassthrough } from \"@langchain/core/runnables\";\n",
        "import { StringOutputParser } from \"@langchain/core/output_parsers\";"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "metadata": {},
      "outputs": [],
      "source": [
        "import { createStuffDocumentsChain } from \"langchain/chains/combine_documents\";\n",
        "\n",
        "const loader = new CheerioWebBaseLoader(\n",
        "  \"https://lilianweng.github.io/posts/2023-06-23-agent/\"\n",
        ");\n",
        "\n",
        "const docs = await loader.load();\n",
        "\n",
        "const textSplitter = new RecursiveCharacterTextSplitter({ chunkSize: 1000, chunkOverlap: 200 });\n",
        "const splits = await textSplitter.splitDocuments(docs);\n",
        "const vectorStore = await MemoryVectorStore.fromDocuments(splits, new OpenAIEmbeddings());\n",
        "\n",
        "// Retrieve and generate using the relevant snippets of the blog.\n",
        "const retriever = vectorStore.asRetriever();\n",
        "const prompt = await pull<ChatPromptTemplate>(\"rlm/rag-prompt\");\n",
        "const llm = new ChatOpenAI({ modelName: \"gpt-3.5-turbo\", temperature: 0 });\n",
        "const ragChain = await createStuffDocumentsChain({\n",
        "  llm,\n",
        "  prompt,\n",
        "  outputParser: new StringOutputParser(),\n",
        "});"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "\u001b[32m\"Task decomposition is a technique used to break down complex tasks into smaller and simpler steps. I\"\u001b[39m... 208 more characters"
            ]
          },
          "execution_count": 7,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "await ragChain.invoke({\n",
        "  context: await retriever.invoke(\"What is Task Decomposition?\"),\n",
        "  question: \"What is Task Decomposition?\"\n",
        "});"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Contextualizing the question\n",
        "\n",
        "First we'll need to define a sub-chain that takes historical messages and the latest user question, and reformulates the question if it makes reference to any information in the historical information.\n",
        "\n",
        "We'll use a prompt that includes a `MessagesPlaceholder` variable under the name \"chat_history\". This allows us to pass in a list of Messages to the prompt using the \"chat_history\" input key, and these messages will be inserted after the system message and before the human message containing the latest question."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "metadata": {},
      "outputs": [],
      "source": [
        "import { ChatPromptTemplate, MessagesPlaceholder } from \"@langchain/core/prompts\";\n",
        "\n",
        "const contextualizeQSystemPrompt = `Given a chat history and the latest user question\n",
        "which might reference context in the chat history, formulate a standalone question\n",
        "which can be understood without the chat history. Do NOT answer the question,\n",
        "just reformulate it if needed and otherwise return it as is.`;\n",
        "\n",
        "const contextualizeQPrompt = ChatPromptTemplate.fromMessages([\n",
        "  [\"system\", contextualizeQSystemPrompt],\n",
        "  new MessagesPlaceholder(\"chat_history\"),\n",
        "  [\"human\", \"{question}\"]\n",
        "]);\n",
        "const contextualizeQChain = contextualizeQPrompt.pipe(llm).pipe(new StringOutputParser());"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Using this chain we can ask follow-up questions that reference past messages and have them reformulated into standalone questions:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "\u001b[32m'What is the definition of \"large\" in the context of a language model?'\u001b[39m"
            ]
          },
          "execution_count": 6,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "import { AIMessage, HumanMessage } from \"@langchain/core/messages\";\n",
        "\n",
        "await contextualizeQChain.invoke({\n",
        "  chat_history: [\n",
        "    new HumanMessage(\"What does LLM stand for?\"),\n",
        "    new AIMessage(\"Large language model\") \n",
        "  ],\n",
        "  question: \"What is meant by large\",\n",
        "})"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Chain with chat history\n",
        "\n",
        "And now we can build our full QA chain. \n",
        "\n",
        "Notice we add some routing functionality to only run the \"condense question chain\" when our chat history isn't empty. Here we're taking advantage of the fact that if a function in an LCEL chain returns another chain, that chain will itself be invoked."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "metadata": {},
      "outputs": [],
      "source": [
        "import { ChatPromptTemplate, MessagesPlaceholder } from \"@langchain/core/prompts\"\n",
        "import { RunnablePassthrough, RunnableSequence } from \"@langchain/core/runnables\";\n",
        "import { formatDocumentsAsString } from \"langchain/util/document\";\n",
        "\n",
        "const qaSystemPrompt = `You are an assistant for question-answering tasks.\n",
        "Use the following pieces of retrieved context to answer the question.\n",
        "If you don't know the answer, just say that you don't know.\n",
        "Use three sentences maximum and keep the answer concise.\n",
        "\n",
        "{context}`\n",
        "\n",
        "const qaPrompt = ChatPromptTemplate.fromMessages([\n",
        "  [\"system\", qaSystemPrompt],\n",
        "  new MessagesPlaceholder(\"chat_history\"),\n",
        "  [\"human\", \"{question}\"]\n",
        "]);\n",
        "\n",
        "const contextualizedQuestion = (input: Record<string, unknown>) => {\n",
        "  if (\"chat_history\" in input) {\n",
        "    return contextualizeQChain;\n",
        "  }\n",
        "  return input.question;\n",
        "};\n",
        "\n",
        "const ragChain = RunnableSequence.from([\n",
        "  RunnablePassthrough.assign({\n",
        "    context: (input: Record<string, unknown>) => {\n",
        "      if (\"chat_history\" in input) {\n",
        "        const chain = contextualizedQuestion(input);\n",
        "        return chain.pipe(retriever).pipe(formatDocumentsAsString);\n",
        "      }\n",
        "      return \"\";\n",
        "    },\n",
        "  }),\n",
        "  qaPrompt,\n",
        "  llm\n",
        "])"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "AIMessage {\n",
            "  lc_serializable: true,\n",
            "  lc_kwargs: {\n",
            "    content: \"Task decomposition is a technique used to break down complex tasks into smaller and more manageable \"... 278 more characters,\n",
            "    additional_kwargs: { function_call: undefined, tool_calls: undefined }\n",
            "  },\n",
            "  lc_namespace: [ \"langchain_core\", \"messages\" ],\n",
            "  content: \"Task decomposition is a technique used to break down complex tasks into smaller and more manageable \"... 278 more characters,\n",
            "  name: undefined,\n",
            "  additional_kwargs: { function_call: undefined, tool_calls: undefined }\n",
            "}\n"
          ]
        },
        {
          "data": {
            "text/plain": [
              "AIMessage {\n",
              "  lc_serializable: \u001b[33mtrue\u001b[39m,\n",
              "  lc_kwargs: {\n",
              "    content: \u001b[32m\"Common ways of task decomposition include using prompting techniques like Chain of Thought (CoT) or \"\u001b[39m... 332 more characters,\n",
              "    additional_kwargs: { function_call: \u001b[90mundefined\u001b[39m, tool_calls: \u001b[90mundefined\u001b[39m }\n",
              "  },\n",
              "  lc_namespace: [ \u001b[32m\"langchain_core\"\u001b[39m, \u001b[32m\"messages\"\u001b[39m ],\n",
              "  content: \u001b[32m\"Common ways of task decomposition include using prompting techniques like Chain of Thought (CoT) or \"\u001b[39m... 332 more characters,\n",
              "  name: \u001b[90mundefined\u001b[39m,\n",
              "  additional_kwargs: { function_call: \u001b[90mundefined\u001b[39m, tool_calls: \u001b[90mundefined\u001b[39m }\n",
              "}"
            ]
          },
          "execution_count": 10,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "let chat_history = [];\n",
        "\n",
        "const question = \"What is task decomposition?\";\n",
        "const aiMsg = await ragChain.invoke({ question, chat_history });\n",
        "console.log(aiMsg)\n",
        "chat_history = chat_history.concat(aiMsg);\n",
        "\n",
        "const secondQuestion = \"What are common ways of doing it?\";\n",
        "await ragChain.invoke({ question: secondQuestion, chat_history });"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "See the first [LastSmith trace here](https://smith.langchain.com/public/527981c6-5018-4b68-a11a-ebcde77843e7/r) and the [second trace here](https://smith.langchain.com/public/7b97994a-ab9f-4bf3-a2e4-abb609e5610a/r)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Here we've gone over how to add application logic for incorporating historical outputs, but we're still manually updating the chat history and inserting it into each input. In a real Q&A application we'll want some way of persisting chat history and some way of automatically inserting and updating it.\n",
        "\n",
        "For this we can use:\n",
        "\n",
        "- [BaseChatMessageHistory](/docs/modules/memory/chat_messages/): Store chat history.\n",
        "- [RunnableWithMessageHistory](/docs/expression_language/how_to/message_history): Wrapper for an LCEL chain and a `BaseChatMessageHistory` that handles injecting chat history into inputs and updating it after each invocation.\n",
        "\n",
        "For a detailed walkthrough of how to use these classes together to create a stateful conversational chain, head to the [How to add message history (memory)](/docs/expression_language/how_to/message_history) LCEL page."
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Deno",
      "language": "typescript",
      "name": "deno"
    },
    "language_info": {
      "file_extension": ".ts",
      "mimetype": "text/x.typescript",
      "name": "typescript",
      "nb_converter": "script",
      "pygments_lexer": "typescript",
      "version": "5.3.3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 2
}
